package com.icangya.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icangya.DAO.*;
import com.icangya.domain.*;
import com.icangya.service.IMoneyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service("MoneyServiceImpl")
public class MoneyServiceImpl  implements IMoneyService{

    @Autowired
    private IBalanceDAO iBalanceDAO;

    @Autowired
    private ICommissionFootDAO iCommissionFootDAO;

    @Autowired
    private IExpendRecordDAO iExpendRecordDAO;

    @Autowired
    private ICommissionRecordDAO iCommissionRecordDAO;

    @Autowired
    private ICashRegisterDAO iCashRegisterDAO;

    @Autowired
    private IGiftAdvertMoneyDAO iGiftAdvertMoneyDAO;

    @Autowired
    private IRechargeRecordDAO iRechargeRecordDAO;

    @Autowired
    private IAliPayCashRecordDAO iAliPayCashRecordDAO;

    @Autowired
    private IUserFootDAO iUserFootDAO;

    @Autowired
    private IGainRecordDAO iGainRecordDAO;

    @Override
    public void saveBalance(Balance balance) {

        iBalanceDAO.save(balance);
    }

    @Override
    public void saveCommission(Commission commission) {

        iCommissionFootDAO.save(commission);

    }

    @Override
    public void saveGiftAdvertMoney(GiftAdvertMoney giftAdvertMoney) {
        iGiftAdvertMoneyDAO.save(giftAdvertMoney);
    }

    @Override
    public Balance getUserBalanceByOpenId(String openId) {
        return iBalanceDAO.getBanlanceByOpenId(openId);
    }

    @Override
    public Commission getUserCommissionyByOpenId(String openId) {
        return iCommissionFootDAO.selectUserCommis(openId);
    }

    @Override
    public int updateCommission(String openId, double money) {
        Commission commission=  iCommissionFootDAO.selectUserCommis(openId);
        if(commission!=null){
            money=commission.getMoney()+money;
            return iCommissionFootDAO.changeMoney(openId,money);
        }
        return 0;
    }

    @Override
    public void saveCommissionRecord(CommissionRecord commissionRecord) {
        iCommissionRecordDAO.save(commissionRecord);
    }

    //用户支出记录
    @Override
    public JSONObject getExpendRecord(String openId) {
        List list;
        list=iExpendRecordDAO.getExpendRecordByOpenId(openId);
        if(list==null)
            return null;
        JSONArray jsonArray= getExpendArray(( List<ExpendRecord>)list);
//        JSONArray jsonArray=new JSONArray();
//        for (ExpendRecord er:(List<ExpendRecord>)list) {
//            JSONObject jsonObject=new JSONObject();
//            jsonObject.put("money",er.getExpendMoney());
//            jsonObject.put("expendTime",er.getExpendTime());
//            jsonObject.put("expendType",er.getExpendType());
//            jsonObject.put("openId",er.getOpenId());
//            jsonArray.add(jsonObject);
//
//        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("value",jsonArray);
        return jsonObject;
    }
    //用户获得广告金支出记录
    @Override
    public JSONObject getExpendRecordMoney(String openId, int startPage) {

        //用户发布广告的支出记录
        List list=  iExpendRecordDAO.getExpendRecordByOpenId(openId,startPage);

        if(list!=null){
            JSONArray jsonArray= getExpendArray(( List<ExpendRecord>)list.get(0));
            //JSONArray jsonArray=new JSONArray();
//            for (ExpendRecord expendRecord:( List<ExpendRecord>)list.get(0)) {
//                JSONObject jsonObject=new JSONObject();
//                jsonObject.put("openId",expendRecord.getOpenId());
//                jsonObject.put("expendMoney",expendRecord.getExpendMoney());
//                jsonObject.put("expendType",expendRecord.getExpendType());
//                jsonObject.put("expendTime",expendRecord.getExpendTime());
//                jsonArray.add(jsonObject);
//
//            }
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("value",jsonArray);
            jsonObject.put("totalPage",list.get(1));
            jsonObject.put("inPage",list.get(2));
            return jsonObject;
        }
        return null;
    }

    JSONArray getExpendArray(List <ExpendRecord> list){
        JSONArray jsonArray=new JSONArray();
        for (ExpendRecord expendRecord:list) {
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("openId",expendRecord.getOpenId());
            double bmoney=expendRecord.getExpendMoney();
            BigDecimal big=new BigDecimal(bmoney);
            double money=big.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();//设置添加到数据库的金额只包含俩位小数

            jsonObject.put("expendMoney",money);
            jsonObject.put("expendType",expendRecord.getExpendType());
            jsonObject.put("expendTime",expendRecord.getExpendTime());
            jsonArray.add(jsonObject);

        }
        return jsonArray;
    }

    //用户获取佣金的记录
    @Override
    public JSONObject getCommRecord(String openId,int startPage) {
        List list;
        List    listStart = null;
        if(startPage>0){
          listStart=iCommissionRecordDAO.getCommRecordByOpenId(startPage,openId);
            list=(List<CommissionRecord>)listStart.get(0);
        }else{
            list=iCommissionRecordDAO.getCommissionRecordByOpenId(openId);
        }

        if(list==null)
            return null;

        JSONArray jsonArray=new JSONArray();
        for (CommissionRecord cr:(List<CommissionRecord>)list) {
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("money",cr.getCommissionMoney());
            jsonObject.put("commTime",cr.getCommissionTime());
            jsonObject.put("commType",cr.getCommissionType());
            jsonObject.put("openId",cr.getOpenId());
            jsonArray.add(jsonObject);

        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("value",jsonArray);
        if(startPage>0){
            jsonObject.put("totalPage",listStart.get(1));
            jsonObject.put("inPage",listStart.get(2));
        }
        return jsonObject;
    }





    @Override
    public JSONObject getCashRecord(String openId) {
        List list;
        list=iCashRegisterDAO.getCashRecordByOpenId(openId);
        if(list==null)
            return null;

//        JSONArray jsonArray=new JSONArray();
//        for (CashRegister c:(List<CashRegister>) list) {
//            JSONObject jsonObject=new JSONObject();
//            jsonObject.put("openId",c.getOpenId());
//            jsonObject.put("money",c.getMoney());
//            jsonObject.put("createTime",c.getCreateTime());
//            jsonObject.put("status",c.getStatus());
//            jsonArray.add(jsonObject);
//        }
        JSONArray jsonArray=getJsonArray((List<CashRegister>) list.get(0));
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("value",jsonArray);
        
        return jsonObject;
    }

    //用户提现记录
    @Override
    public JSONObject getCashRecord(String openId, int startPage) {

        List list;
        list=iCashRegisterDAO.getCashRecordByOpenId(openId,startPage);
        if(list==null)
            return null;

        //JSONArray jsonArray=new JSONArray();
        JSONArray jsonArray=getJsonArray((List<CashRegister>) list.get(0));
//        for (CashRegister c:(List<CashRegister>) list.get(0)) {
//            JSONObject jsonObject=new JSONObject();
//            jsonObject.put("openId",c.getOpenId());
//            jsonObject.put("money",c.getMoney());
//            jsonObject.put("createTime",c.getCreateTime());
//            jsonObject.put("status",c.getStatus());
//            jsonArray.add(jsonObject);
//        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("value",jsonArray);
        jsonObject.put("totalPage",list.get(1));
        jsonObject.put("inPage",list.get(2));
        return jsonObject;
    }

    JSONArray getJsonArray(List<CashRegister> list){
        JSONArray jsonArray=new JSONArray();
        for (CashRegister c: list) {
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("openId",c.getOpenId());
            jsonObject.put("money",c.getMoney());
            jsonObject.put("createTime",c.getCreateTime());
            jsonObject.put("status",c.getStatus());
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }
    //用户获得广告金充值记录
    @Override
    public JSONObject getRechargeRecordMoney(String openId, int startPage) {

        //用户充值的记录
        List list= iRechargeRecordDAO.getRechargeRecordByOpenId(openId,startPage);


        if(list!=null){
            JSONArray jsonArray=new JSONArray();
            for (RechargeRecord r:(List<RechargeRecord>) list.get(0)) {
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("openId",r.getOpenId());
                jsonObject.put("money",r.getMoney());
                jsonObject.put("rechargeTime",r.getRechargeTime());
                jsonObject.put("status",r.getStatus());
                jsonArray.add(jsonObject);
            }
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("value",jsonArray);
            jsonObject.put("totalPage",list.get(1));
            jsonObject.put("inPage",list.get(2));
            return jsonObject;
        }
        return null;
    }


    /**
     * 测试用户能否看广告
     * @param openId
     * @return
     */
    @Override
    public Boolean getRechargeRecord(String openId) {
      List<RechargeRecord> list=  iRechargeRecordDAO.getRechargeRecordByOpenId(openId);
      if(list==null)
          return false;

//        RechargeRecord rechargeRecord=list.get(0);
//
//        Date mDate = rechargeRecord.getRechargeTime();
//        Date date = new Date();

      RechargeRecord rechargeRecord=list.get(0);
//        Date mDate = rechargeRecord.getRechargeTime();
//        Date date = new Date();
//        double timeDiff = (int) (date.getTime() - mDate.getTime()) / (1000 * 3600 );
//        if (timeDiff <= 24)//设置查看广告时间，默认一天
//            return true;

        SimpleDateFormat fmt=new SimpleDateFormat("yyyy-MM-dd");
        if(fmt.format(rechargeRecord.getRechargeTime()).equals(fmt.format(new Date()).toString()))
            return true;
        return false;
    }


//* 支付宝提现佣金记录
    @Override
    public AliPayCashRecord saveAliPay(AliPayCashRecord aliPayCashRecord) {

      Commission commission=  getUserCommissionyByOpenId(aliPayCashRecord.getOpenId());//获取用户佣金余额
        if(commission==null || commission.getMoney() < 1){
            System.out.print("commission.getMoney()======"+commission.getMoney());
            return null;
        }
        System.out.print("commission.getMoney()===do==="+commission.getMoney());
        aliPayCashRecord.setMoney(commission.getMoney());
        AliPayCashRecord aliPayCash= iAliPayCashRecordDAO.get(iAliPayCashRecordDAO.save(aliPayCashRecord));
        if(aliPayCash!=null){
            int result=  iCommissionFootDAO.changeMoney(aliPayCash.getOpenId(),0); //修改用户佣金为0
        }

        return  aliPayCash;
    }

   //  获取所有待审核中的使用支付宝提现的用户
    @Override
    public JSONObject getAliPayAll(int startPage) {

      List list=  iAliPayCashRecordDAO.getAliPayRecord(startPage);
        if(list==null)
        return null;
        if((int)list.get(1)<startPage)
            return null;
        JSONArray jsonArray=new JSONArray();
        for (AliPayCashRecord al:(List<AliPayCashRecord>)list.get(0)) {

            JSONObject jsonObject=new JSONObject();
            Object[] obj = iUserFootDAO.getNickName(al.getOpenId());

            if (obj == null) {
                continue;
            }
            jsonObject.put("nickName",obj[0]);//获得用户昵称
            jsonObject.put("headImgUrl",obj[1]);//用户头像
//           User user= iUserFootDAO.selectUserByOpenId(al.getOpenId());
//           if(user==null)
//               continue;//当用户为空时结束本轮循环
//            jsonObject.put("nickName",user.getNickName());
//            jsonObject.put("headImgUrl",user.getHeadImgUrl());

//           User user= iUserFootDAO.selectUserByOpenId(al.getOpenId());
//           if(user==null)
//               continue;//当用户为空时结束本轮循环
//            jsonObject.put("nickName",user.getNickName());
//            jsonObject.put("headImgUrl",user.getHeadImgUrl());
            jsonObject.put("id",al.getId());
            jsonObject.put("aliPayAccount",al.getAliPayAccount());
            jsonObject.put("money",al.getMoney());
            jsonObject.put("statusValue",al.getStatusValue());

            jsonArray.add(jsonObject);

        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("value",jsonArray);
        jsonObject.put("totalPage",list.get(1));
        jsonObject.put("inPage",list.get(2));
        if(jsonArray==null){
            jsonObject.put("totalPage",0);
            jsonObject.put("inPage",0);
        }

        return jsonObject;

    }

    @Override
    public Boolean setApprove(long aliPayId) {
      AliPayCashRecord aliPayCashRecord=  iAliPayCashRecordDAO.get(aliPayId);
        boolean bool=false;
      if(aliPayCashRecord==null)
          return bool;

          aliPayCashRecord.setStatus(0);
          aliPayCashRecord.setStatusValue("提现成功");
        bool=iAliPayCashRecordDAO.update(aliPayCashRecord);
        if(bool){
            //
            //修改成功，将体现记录增加到微信提现记录表中
            iCashRegisterDAO.save(new CashRegister(aliPayCashRecord.getOpenId(),aliPayCashRecord.getMoney(),new Timestamp(new Date().getTime()),0) );
            return bool;
        }

        return bool;


    }

    @Override
    public Boolean failureAudit(long aliPayId) {
        AliPayCashRecord aliPayCashRecord=  iAliPayCashRecordDAO.get(aliPayId);
        boolean bool=false;
        if(aliPayCashRecord==null)
            return bool;

        aliPayCashRecord.setStatus(2);
        aliPayCashRecord.setStatusValue("审核失败");
        bool=iAliPayCashRecordDAO.update(aliPayCashRecord);
        if(bool){
            //审核失败，将金额修改回用户佣金表
            Commission commission=  getUserCommissionyByOpenId(aliPayCashRecord.getOpenId());//获取用户佣金余额
            double money=commission.getMoney()+aliPayCashRecord.getMoney();
            int result=  iCommissionFootDAO.changeMoney(aliPayCashRecord.getOpenId(),money);
            if(result>0)
            return true;
        }

        return bool;
    }

    @Override
    public Double getRechargeMoneyNow(Timestamp time) {
        return iRechargeRecordDAO.getRechargeMoneyNow(time);
    }

    @Override
    public Double getCashMoneyNow(Timestamp time) {

        return iCashRegisterDAO.getCashMoneyNow(time);
    }

    @Override
    public GainRecord getGainRecordTime(Timestamp startTime, Timestamp endTime) {

        GainRecord gainRecord=  iGainRecordDAO.getGainTime(startTime,endTime);

        return gainRecord;
    }

    @Override
    public void saveGainRecord(GainRecord gainRecord) {

        iGainRecordDAO.save(gainRecord);
    }

    @Override
    public JSONObject getGainRecordAll(int startPage) {

        List list=iGainRecordDAO.getGainAll(startPage);
        if(list==null){
            return null;
        }
        if((int)list.get(1)<startPage)
            return null;

        JSONArray jsonArray=new JSONArray();
        for (GainRecord gainRecord:(List<GainRecord>)list.get(0)) {
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("expendMoney",gainRecord.getExpendMoney());//支出金额
            jsonObject.put("gainMoney",gainRecord.getGainMoney());//实际收入
            jsonObject.put("id",gainRecord.getId());
            jsonObject.put("rechargeMoney",gainRecord.getRechargeMoney());
            jsonObject.put("createTime",gainRecord.getCreateTime());
            jsonArray.add(jsonObject);

        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("value",jsonArray);
        jsonObject.put("totalPage",list.get(1));
        jsonObject.put("inPage",list.get(2));
        return jsonObject;
    }
}
























